﻿@using WishlistUtilities;
@using System.Collections;
@{

    PageData["Title"] = "User Management";

	WebSecurity.RequireAuthenticatedUser();
    if (!Roles.IsUserInRole("admin")) {
    	Response.Redirect("~");
    }

	var db = Database.Open("wishlistdb");
    var errorMessage = "";
    dynamic item = null;
    
    if (IsPost) {
        if (Request["action"].IsEmpty()) {
			Response.Redirect("~/Shared/Errors/Errors/Error");
		} else {    
            if (Request["action"] == "Update") {
                var userToEdit = Request["user_id"];
                var userNameToEdit = Request["user_username"];
                if (!userToEdit.IsEmpty() &&
                    !Request["firstName"].IsEmpty() &&
                    !Request["lastName"].IsEmpty() &&
                    !Request["email"].IsEmpty() && ValidationUtility.IsValidEmail(Request["email"]))
                    {
                        try {
                            db.Execute(@"UPDATE WishlistUser SET FirstName=@0, LastName=@1, Email=@2 WHERE Id=@3", 
                                Request["firstName"], Request["lastName"], Request["email"], userToEdit);
                        
                            //Aside from updating the information in the user table, we also need to update roles
                            foreach(string role in Roles.GetAllRoles()) {
                                if(!(userNameToEdit == WebSecurity.CurrentUserName && role == "admin")) {
                                    if (Request["is" + role].AsBool()) {
                                        if (!Roles.IsUserInRole(userNameToEdit, role)) {
                                            Roles.AddUserToRole(userNameToEdit, role);
                                        }
                                    } else {
                                        if (Roles.IsUserInRole(userNameToEdit, role)) {
                                            Roles.RemoveUserFromRole(userNameToEdit, role);
                                        }
                                    }
                                }
                            }
                          
                        } catch (Exception) {
                        Response.Redirect("~/Shared/Errors/Error");
                    }                
                } else {
                    errorMessage = "<li>First Name, Last Name, or E-mail cannot be empty.  Make sure e-mail is in a correct format.</li>";
                }
                
                Response.Redirect("~/Admin/UserManagement.cshtml");                 
                } else if (Request["action"] == "Cancel") {
                    Response.Redirect("~/Admin/UserManagement.cshtml");
                }
            }
    } else {
        if(!IsPost && !UrlData[0].IsEmpty()) {
            item = db.QuerySingle("SELECT * FROM WishlistUser WHERE Username = @0",UrlData[0]);  
            PageData[0] = item;
        }
    }
}

    @if (!errorMessage.IsEmpty()) {
        @RenderPage("~/Shared/Errors/_FormInputError.cshtml", errorMessage);
    }
        
<div id="detail">
    @if(item!=null){	    
    <div>
	    <form id="validateForm" method="post" action="EditUser.cshtml">
	        <fieldset>
	            <legend>Edit User Information</legend>
		        @RenderPage("~/Shared/_EditUserTemplate.cshtml")
		        <div class="submit-group">
			        <input name="action" type="submit" value="Update" onclick="javascript:$('#validateForm').validate()" />
			        <input name="action" type="submit" value="Cancel"/>
		        </div>
	        </fieldset>
	    </form>
	    </div>    	
    }
</div>